package service;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.Kv;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import common.kit.ImageKits;
import common.kit.PageSql;
import common.kit.PropKits;
import enums.CompanyStatus;
import enums.RunRecordsRealType;
import enums.StationStatus;
import enums.StationType;
import model.Company;
import model.RunRecords;
import model.Staff;
import model.Station;
import model.Wxuser;

public class StationService extends BaseService {

	public List<Map<String, Object>> getStationStatusList() {
		List<Map<String, Object>> list = StationStatus.toList() ;
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("title", "全部");
		map.put("value", "");
		list.add(0, map);
		return list ;
	}
	
	public Ret delete(Long id) {
        Station station = Station.dao.findById(id);
        if(null == station){
            return fail();
        }
        return station.delete() ? ok() : fail() ;
    }

	public Page<Record> getApiPage(Kv kv , Integer pageNumber , Integer pageSize) {
		kv.set("ts.isDelete",0);
		String select = "tsr.name AS servicerName ,tsf.name AS staffName,tsf.mobile AS staffMobile , ts.id,ts.name,ts.address,ts.latitude,ts.longitude,ts.qrcode,ts.status,ts.type,tc.name AS companyName " ;
	    PageSql pageSql = PageSql.bySelect( kv , select ) ;
	    pageSql.from(" t_station ts ") ;
	    pageSql.join(" t_company tc " , " tc.id = ts.companyId ") ;
	    pageSql.join(" t_staff tsf " , " tsf.id = ts.staffId ") ;
	    pageSql.join(" t_servicer tsr " , " tsr.id = tsf.servicerId ") ;
		pageSql.setEqualCondition("ts.companyId") ; //所属企业
		pageSql.setEqualCondition("ts.status") ; //状态	 
		pageSql.setEqualCondition("ts.id") ;
		pageSql.setEqualCondition("ts.isDelete") ; //状态	 
	    pageSql.orderBy(" ts.createTime DESC ");
		Page<Record> page = pageSql.paginate( pageNumber , pageSize) ;
		for (Record record : page.getList()) {
			record.set("statusStr", StationStatus.getTitleByValue(record , "status"));
//			record.set("typeStr", StationType.getTitleByValue(record , "type"));
			record.set("qrcode", this.createQrcode(record.getLong("id")));
		}
	    return page ;
	}
	
	public List<Record> listByCompany(Long companyId) {
		List<Record> list = Db.find(" SELECT tsr.name AS servicerName ,tsf.name AS staffName,tsf.mobile AS staffMobile , ts.id,ts.name,ts.address,ts.latitude,ts.longitude,ts.qrcode,ts.status,ts.type FROM t_station ts LEFT JOIN t_staff tsf ON tsf.id = ts.staffId LEFT JOIN t_servicer tsr ON tsr.id = tsf.servicerId WHERE ts.companyId = ? AND ts.isDelete = 0 ORDER BY ts.createTime DESC " , companyId );
		for (Record record : list) {
			record.set("statusStr", StationStatus.getTitleByValue(record , "status"));
			record.set("qrcode", this.createQrcode(record.getLong("id")));
		}
		return list ;
	}
	
	
	public Page<Record> getApiPages(Kv kv , Integer pageNumber , Integer pageSize) {
		kv.set("ts.isDelete",0);
		String select = "tsr.id,tc.name,tc.contacts,tc.mobile,tc.id AS companyId,tc.address,tsr.name AS serviers,tc.status" ;
	    PageSql pageSql = PageSql.bySelect( kv , select ) ;
	    pageSql.from(" t_station ts ") ;
	    pageSql.join(" t_company tc " , " tc.id = ts.companyId ") ;
	    pageSql.join(" t_servicer_company tsc " , " tsc.companyId = ts.companyId ") ;
	    pageSql.join(" t_servicer tsr " , " tsr.id = tsc.serviserId ") ;
		pageSql.setEqualCondition("tsr.id") ; //运维公司
		pageSql.setEqualCondition("ts.companyId") ; //所属企业
		pageSql.setEqualCondition("ts.status") ; //状态	 
		pageSql.setEqualCondition("ts.id") ;
		pageSql.setEqualCondition("ts.isDelete") ; //状态	 
		pageSql.setLikeCondition("ts.area");
		pageSql.setLikeCondition("ts.monitorNum"); //所属行业
		pageSql.setLikeCondition("ts.type"); //站位类型
		pageSql.setLikeCondition("ts.controlLevel"); //站位级别
		pageSql.setLikeCondition("tc.name"); //企业名称
		pageSql.setLikeCondition("tsr.name"); //企业名称
	    pageSql.orderBy(" ts.createTime DESC ");
	    pageSql.groupBy("ts.companyId");
		Page<Record> page = pageSql.paginate( pageNumber , pageSize) ;
		for (Record record : page.getList()) {
			record.set("statusStr", CompanyStatus.getTitleByValue(record , "status"));
//			record.set("typeStr", StationType.getTitleByValue(record , "type"));
//			record.set("qrcode", this.createQrcode(record.getLong("id")));
		}
	    return page ;
	}
	
	
	public String createQrcode(Long stationId) {
		String domain = PropKits.getWebdomain() ;
		String name = "from_" + stationId ;
		String currentPath = "/download/qrcode/" + name + ".png" ;
		File file = new File(PathKit.getWebRootPath() +  currentPath);
		if (file.exists()) {
			return domain + currentPath ;
		}
		//将二维码下载到本地
		JSONObject map = new JSONObject();
		map.put("scene", name );
		map.put("page", "pages/stationList/stationList");
		map.put("width", 600);
		ImageKits.getQrcode(currentPath , map);
		return domain + currentPath ; 
	}
	
	public Page<Record> getMyApiPage(Kv kv , Integer pageNumber , Integer pageSize) {
		kv.set("ts.isDelete",0);
		String select = " tsr.name AS servicerName ,tsf.name AS staffName,tsf.mobile AS staffMobile ,ts.id,ts.name,ts.address,ts.latitude,ts.longitude,ts.qrcode,ts.status,ts.type,tc.name AS companyName " ;
	    PageSql pageSql = PageSql.bySelect( kv , select ) ;
	    pageSql.from(" t_station ts ") ;
	    pageSql.join(" t_company tc " , " tc.id = ts.companyId ") ;
	    pageSql.join(" t_staff tsf " , " tsf.id = ts.staffId ") ;
	    pageSql.join(" t_servicer tsr " , " tsr.id = tsf.servicerId ") ;
		pageSql.setEqualCondition("ts.companyId") ; //所属企业	 
		pageSql.setEqualCondition("ts.id") ; 
		pageSql.setEqualCondition("ts.status") ; //状态
		pageSql.setEqualCondition("ts.isDelete") ; //状态	 
	    pageSql.orderBy(" ts.createTime DESC ");
		Page<Record> page = pageSql.paginate( pageNumber , pageSize) ;
		for (Record record : page.getList()) {
			record.set("statusStr", StationStatus.getTitleByValue(record , "status"));
			record.set("qrcode", this.createQrcode(record.getLong("id")));
		}
	    return page ;
	}
	
	public Ret save(Station station , Wxuser wxuser) {
		if (!wxuser.isStaffRole()) {
			return fail("非运维人员禁止操作");
		}
		Staff staff = Staff.dao.findFirstByWxuser(wxuser);
		if (null == staff) {
			return fail("未查询到职员信息");
		}
		Long id = station.getId();
		station.setStaffId(staff.getId());
		if (null == id) {
			station.setNormalStatus();
			station.save();
		}else {
			station.update();
		}
		return ok() ;
	}
	
	public Ret delete(Station station) {
		if (station.getIsDelete()) {
			return ok();
		}
		station.setIsDelete(true);
		station.update();
		return ok() ;
	}
	

	public Page<Record> getPage(Kv kv , Integer pageNumber , Integer pageSize) {
		String select = " ts.id,ts.name,ts.latitude,ts.longitude,ts.status,ts.type,tc.name AS companyName,tsf.name AS staffName1,tsr.name AS servicerName2 " ;
	    PageSql pageSql = PageSql.bySelect( kv , select ) ;
	    pageSql.from(" t_station ts ") ;
	    pageSql.join(" t_company tc " , " tc.id = ts.companyId ") ;
	    pageSql.join(" t_staff tsf " , " tsf.id = ts.staffId ") ;
	    pageSql.join(" t_servicer tsr " , " tsr.id = tsf.servicerId ") ;
		pageSql.setLikeCondition("ts.companyId") ;
		pageSql.setLikeCondition("ts.name") ; //点位名称	 
		pageSql.setEqualCondition("ts.status") ; //状态	 
		pageSql.setEqualCondition("ts.type") ; //类型	 
		pageSql.setLikeCondition("tc.name") ; //企业名称	 
		pageSql.setLikeCondition("tsf.name") ; //运维人员	 
		pageSql.setLikeCondition("tsr.name") ; //运维公司	 
	    pageSql.orderBy(" ts.createTime DESC ");
		Page<Record> page = pageSql.paginate( pageNumber , pageSize) ;
		for (Record record : page.getList()) {
			record.set("statusStr", StationStatus.getTitleByValue(record , "status"));
//			record.set("typeStr", StationType.getTitleByValue(record , "type"));
		}
	    return page ;
	}

	public Record detail(Long id) {
		Kv kv = Kv.by("ts.id", id);
		String select = " ts.name,ts.latitude,ts.longitude,ts.status,ts.type,ts.controlLevel,ts.licenseNum,ts.monitorNum,ts.emissions,ts.emissionReference,ts.height,ts.samplingLocation,ts.velocityMeasurement,ts.measuringSection,ts.samplingType,ts.distance,ts.dilutionRate,ts.gasFlow,ts.samplingPressure,ts.dischargeDirection,ts.dealCapacity,ts.emissionMode,ts.modeType,ts.width,ts.dischargeLength,tc.name AS companyName,tsf.name AS staffName1,tsr.name AS servicerName2 " ;
	    PageSql pageSql = PageSql.bySelect( kv , select ) ;
	    pageSql.from(" t_station ts ") ;
	    pageSql.join(" t_company tc " , " tc.id = ts.companyId ") ;
	    pageSql.join(" t_staff tsf " , " tsf.id = ts.staffId ") ;
	    pageSql.join(" t_servicer tsr " , " tsr.id = tsf.servicerId ") ;
	    pageSql.setEqualCondition("ts.id");
	    pageSql.orderBy(" ts.createTime DESC ");
		Record record = pageSql.findFirst() ;
	    record.set("statusStr", StationStatus.getTitleByValue(record.getInt("status")));
	    record.set("typeStr", StationType.getTitleByValue(record.getInt("type")));
	    return record ;
    }
	
	public void changeStatusTask() {
		int pageNumber = 0 ;
		boolean lastPage =false ;
		do {
			pageNumber ++ ;
			Page<Station> page = Station.dao.paginate(pageNumber, 500 , "SELECT ts.id , ts.companyId " , "FROM t_station ts WHERE ts.isDelete = 0 ");
			List<Station> list = page.getList();
			lastPage = page.isLastPage();
			for (Station station : list) {
				this.changeRunStatus(station);
			}
		} while (!lastPage);
		
		this.setCompanyStatus();
	}
	
	public void setCompanyStatus() {
		int pageNumber = 0 ;
		boolean lastPage =false ;
		do {
			pageNumber ++ ;
			Page<Company> page = Company.dao.paginate(pageNumber, 500 , "SELECT tc.id " , "FROM t_company tc ");
			List<Company> list = page.getList();
			lastPage = page.isLastPage();
			for (Company company : list) {
				this.changeCompanyStatus(company);
			}
		} while (!lastPage);
	}
	
	public void changeCompanyStatus(Company company) {
		//最近10天未维护
		Station station = Station.dao.findFirstByStatusAndCompanyId(StationStatus.getTen(), company.getId());
		if (null != station) {
			company.setTenStatus();
			company.update();
			return ;
		}
		//7天未维护
		station = Station.dao.findFirstByStatusAndCompanyId(StationStatus.getSeven(), company.getId());
		if (null != station) {
			company.setSevenStatus();
			company.update();
			return ;
		}
		company.setNormalStatus();
		company.update() ;
	}
	
	public void changeRunStatus(Station station) {
		Long id = station.getId() ;
		RunRecords records = RunRecords.dao.findFirst(" SELECT trr.startTime FROM t_run_records trr WHERE trr.stationId = ? AND trr.realType = ? ORDER BY trr.startTime DESC" , id , RunRecordsRealType.getRun() );
		if (null == records || records.getStartTime().getTime() + 10 * 24 * 60 * 60 * 1000 < System.currentTimeMillis() ) {
			station.setTenStatus();
			station.update();
			return ;
		}
		if (records.getStartTime().getTime() + 7 * 24 * 60 * 60 * 1000 < System.currentTimeMillis()) {
			station.setSevenStatus();
			station.update();
			return ;
		}
		if (!station.isNormalStatus()) {
			station.setNormalStatus();
			station.update();
		}
	}
}
